import React, { useState } from 'react';
import { ExpenseCategory, CATEGORY_CONFIG } from '../types';
import { motion } from 'framer-motion';
import { toast } from 'sonner';

interface AddExpenseProps {
  onAdd: (expense: {
    amount: number;
    category: ExpenseCategory;
    description: string;
    date: string;
  }) => void;
  onClose: () => void;
}

const AddExpense: React.FC<AddExpenseProps> = ({ onAdd, onClose }) => {
  const [amount, setAmount] = useState<string>('');
  const [category, setCategory] = useState<ExpenseCategory>('food');
  const [description, setDescription] = useState<string>('');
  const [date, setDate] = useState<string>(new Date().toISOString().split('T')[0]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    // 验证输入
    if (!amount || parseFloat(amount) <= 0) {
      toast.error('请输入有效的金额');
      return;
    }
    
    if (!description.trim()) {
      toast.error('请输入消费描述');
      return;
    }
    
    // 添加消费记录 - 增强版，添加更严格的验证
    try {
      // 验证金额
      const parsedAmount = parseFloat(amount);
      if (isNaN(parsedAmount) || parsedAmount <= 0) {
        throw new Error('无效的金额');
      }
      
      // 添加消费记录
      onAdd({
        amount: parsedAmount,
        category,
        description: description.trim(),
        date
      });
      
      // 重置表单
      setAmount('');
      setCategory('food');
      setDescription('');
      setDate(new Date().toISOString().split('T')[0]);
      
      toast.success('消费记录已添加');
      
    } catch (error) {
      console.error('Failed to submit expense:', error);
      toast.error('添加消费记录时出错，请重试');
    }
  };

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      exit={{ opacity: 0, y: 20 }}
      transition={{ duration: 0.3 }}
      className="bg-white dark:bg-gray-800 rounded-xl p-5 shadow-lg border border-gray-100 dark:border-gray-700"
    >
      <h2 className="text-xl font-bold text-gray-900 dark:text-white mb-5">添加消费记录</h2>
      
      <form onSubmit={handleSubmit} className="space-y-5">
        <div>
          <label htmlFor="amount" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
            金额 (¥)
          </label>
          <input
            type="number"
            id="amount"
            value={amount}
            onChange={(e) => setAmount(e.target.value)}
            placeholder="请输入金额"
            className="w-full px-4 py-3 rounded-lg border border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-colors"
            step="0.01"
            min="0"
            required
          />
        </div>
        
        <div>
          <label htmlFor="description" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
            描述
          </label>
          <input
            type="text"
            id="description"
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            placeholder="请输入消费描述"
            className="w-full px-4 py-3 rounded-lg border border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-colors"
            required
          />
        </div>
        
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
            类别
          </label>
            <div className="grid grid-cols-4 sm:grid-cols-4 gap-3">
            {Object.entries(CATEGORY_CONFIG).map(([key, config]) => (
              <button
                key={key}
                type="button"
                onClick={() => setCategory(key as ExpenseCategory)}
                className={`flex flex-col items-center p-3 rounded-lg transition-all ${
                  category === key
                    ? 'ring-2 ring-blue-500 bg-blue-50 dark:bg-blue-900/30'
                    : 'bg-gray-50 dark:bg-gray-700 hover:bg-gray-100 dark:hover:bg-gray-600'
                }`}
              >
                <div className={`p-2 rounded-full ${config.color} mb-2`}>
                  <i className={`${config.icon} text-white`}></i>
                </div>
                <span className="text-xs text-gray-700 dark:text-gray-300">{config.name}</span>
              </button>
            ))}
          </div>
        </div>
        
        <div>
          <label htmlFor="date" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
            日期
          </label>
          <input
            type="date"
            id="date"
            value={date}
            onChange={(e) => setDate(e.target.value)}
            className="w-full px-4 py-3 rounded-lg border border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-colors"
            max={new Date().toISOString().split('T')[0]}
            required
          />
        </div>
        
        <div className="flex space-x-3 pt-2">
          <button
            type="button"
            onClick={onClose}
            className="flex-1 px-4 py-3 rounded-lg bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 font-medium hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
          >
            取消
          </button>
          <button
            type="submit"
            className="flex-1 px-4 py-3 rounded-lg bg-blue-500 text-white font-medium hover:bg-blue-600 transition-colors"
          >
            保存记录
          </button>
        </div>
      </form>
    </motion.div>
  );
};

export default AddExpense;